package top.crex1.blogstarter.repository;

import org.springframework.stereotype.Repository;
import top.crex1.blogstarter.domain.User;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;


/**
 * 用户资源库.
 *
 * @author ZZH
 * @date 2018-3-27
 */
@Repository
public class UserRepositoryImpl implements UserRepository {

    private static AtomicLong counter = new AtomicLong();

    private final ConcurrentMap<Long, User> userMap = new ConcurrentHashMap<Long, User>();

    public UserRepositoryImpl() {
        User user = new User();
        user.setAge(22);
        user.setName("zhangzhenghong");
        this.saveOrUpateUser(user);
    }

    /* (non-Javadoc)
     * @see top.crex1.blogstarter.repository.UserRepository#saveUser(top.crex1.blogstarter.vo.UserVO)
     */
    @Override
    public User saveOrUpateUser(User user) {
        Long id = user.getId();
        if (id <= 0) {
            id = counter.incrementAndGet();
            user.setId(id);
        }
        this.userMap.put(id, user);
        return user;
    }

    /* (non-Javadoc)
     * @see top.crex1.blogstarter.repository.UserRepository#deleteUser(java.lang.Long)
     */
    @Override
    public void deleteUser(Long id) {
        this.userMap.remove(id);
    }

    /* (non-Javadoc)
     * @see top.crex1.blogstarter.repository.UserRepository#getUserById(java.lang.Long)
     */
    @Override
    public User getUserById(Long id) {

        return this.userMap.get(id);
    }

    /* (non-Javadoc)
     * @see top.crex1.blogstarter.repository.UserRepository#listUser()
     */
    @Override
    public List<User> listUser() {
        return new ArrayList<User>(this.userMap.values());
    }

}
